import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "@vant/auto-import-resolver";

import os from "os"; // 需要先安装：npm install os

function getLocalIP() {
  console.log("开始获取本机IP..."); // 调试输出

  const interfaces = os.networkInterfaces();
  console.log("检测到的网络接口:", Object.keys(interfaces));

  const ignoreInterfaces = ["VMware", "VirtualBox", "Hyper-V", "vEthernet"]; // 要忽略的虚拟网卡关键词

  for (const devName in interfaces) {
    // 跳过虚拟网卡
    if (ignoreInterfaces.some((keyword) => devName.includes(keyword))) {
      continue;
    }

    const iface = interfaces[devName];
    for (const alias of iface) {
      if (alias.family === "IPv4" && !alias.internal) {
        console.log(`✅ 使用物理网卡 ${devName} 的IP:`, alias.address);
        return alias.address;
      }
    }
  }

  console.warn("⚠️ 未找到物理网卡IP，使用默认localhost");
  return "localhost";
}

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    AutoImport({
      resolvers: [VantResolver()],
    }),
    Components({
      resolvers: [VantResolver()],
    }),
  ],
  base: "/",
  server: {
    host: "0.0.0.0",
    port: 9999,
    open: true,
    proxy: {
      "/api": {
        //获取路径中包含了/api的请求,target是你的springboot服务器的地址
        target: `http://${getLocalIP()}:8081`,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, "/api/v1"), //api替换为''
      },
    },
  },
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
});
